<?php

class Auth {
	
	private static $user = null;
	
	
	public static function checkLoginAttempt() {
		
		$username = null;
		$password = null;
		
		if ((isset($_POST['login']['username']) && $_POST['login']['username'] != '' &&
			isset($_POST['login']['password']) && $_POST['login']['password'] != '')) {
			$username = $_POST['login']['username'];
			$password = $_POST['login']['password'];
		}
		
		
		if ((isset($_SESSION['USERNAME']) && $_SESSION['USERNAME'] != '' &&
			isset($_SESSION['PASSWORD']) && $_SESSION['PASSWORD'] != '')) {
			$username = $_SESSION['USERNAME'];
			$password = $_SESSION['PASSWORD'];
		}
		
		return (Auth::isExistingMember() || Auth::logIn($username, $password));
	}
	
	public static function logIn($username, $password) {
		if (isset($username) && isset($password)) {
			$user = db::getInstance()->getObject('oeUser', '`username`=:username', array('username' => $username));
	        /* @var $user oeUser */
	        if (isset($user) && $user->getId() > 0) {
	           if ($user->isPasswordCorrect($password)) {
	           		if (!isset($_SESSION['USERNAME']))
	           			$_SESSION['USERNAME'] = $username;
	           		if (!isset($_SESSION['PASSWORD']))
	           			$_SESSION['PASSWORD'] = $password;
	                Auth::$user = $user;
	               return true;
	           }
	        }
		}
		return false;
	}
	
	public static function logout() {
		unset($_SESSION['USERNAME']);
		unset($_SESSION['PASSWORD']);
		unset($_POST['login']['username']);
		unset($_POST['login']['password']);
		
		header('Location: /');
		die();
	}
	
	public static function getFirstLogin() {
		if (Auth::checkLoginAttempt()) {
			header('Location: /home-page');
			exit();
		}
		return false;
	}
	
	public static function enforceLogin() {
		if (!Auth::checkLoginAttempt())
			auth::logout();
	}
	
	public static function isExistingMember() {
		return (auth::getMember()->getId() > 0);
	}
	
	public static function getMember() {
		if (isset(auth::$user))
			return auth::$user;
		else
			return new oeUser();
	}
	
	public static function isLoggedIn() {
		return auth::checkLoginAttempt();
	}
	
}